package com.cyy.list;

/**
 * 单向链表
 * @author 会玩的洋洋
 * @since 2022-2-21
 * @param <E>
 */
public class SingleLinkedList<E> extends AbstractList<E>{
    /**
     * 链表虚拟节点
     */
    private Node<E> root;

    public SingleLinkedList() {
        this(new Node<>(null, null));
    }

    public SingleLinkedList(Node<E> root) {
        this.root = new Node<>(root, null);
    }

    @Override
    public void clear() {
        this.root = new Node<>(null, null);
        this.size = 0;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        // 获取目标下标节点
        Node<E> node = node(index);
        E oldElement = node.element;
        // 将获得的节点元素进行覆盖
        node.element = element;
        return oldElement;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckAdd(index);
        ++size;
        // 插入根节点
        if (index == 0) {
            root.next = new Node<>(null, element);
            return;
        }
        // 获取 index 前一个节点
        Node<E> node = node(index - 1);
        node.next = new Node<>(node.next, element);
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);
        Node<E> node = root.next;
        // 如果删除的是第一个节点
        if (index == 0) {
            root.next = node.next;
        } else {
            // 获取要删除节点的前一个节点
            Node<E> prev = node(index - 1);
            node = prev.next;
            prev.next = node.next;
        }
        --size;
        return node.element;
    }

    @Override
    public int indexOf(E element) {
        Node<E> node = root.next;
        if (element == null) {
            for (int i = 0; i < this.size; i++) {
                if (node.element == null) {
                    return i;
                }
                node = node.next;
            }
        } else {
            for (int i = 0; i < this.size; i++) {
                if (node.element.equals(element)) {
                    return i;
                }
                node = node.next;
            }
        }
        return FAILED_RETURN;
    }

    private Node<E> node(int index) {
        this.rangeCheck(index);
        Node<E> node = root.next;

        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("SingleLinkedList{");
        Node<E> node = root.next;
        while (node != null) {
            sb.append("{element=").append(node.element).append("}");
            node = node.next;
        }

        sb.append("}");
        return sb.toString();
    }

    private static class Node<E> {
        Node<E> next;
        E element;

        public Node() {}

        public Node(Node<E> next, E element) {
            this.next = next;
            this.element = element;
        }
    }
}
